import { Component, OnInit, Input,  OnDestroy, OnChanges, SimpleChanges } from '@angular/core';
import { v4 as uuidv4 } from 'uuid';
import { CommonService,MapService,StyleService } from '../../core';
import { NzMessageService } from 'ng-zorro-antd/message';
import Viewer from 'viewerjs';
import { ShareMessageService } from '../../core/services/share-message.service';
@Component({
  selector: 'app-question-mark',
  templateUrl: './question-mark.component.html',
  styleUrls: ['./question-mark.component.scss']
})
export class QuestionMarkComponent implements OnInit, OnChanges, OnDestroy {
  @Input() questionLayerIsOpen = null;
  // 模态框是否显示
  isVisible = false;
  data;
  // 设置状态是否是查看详情状态
  flag = false;
  imginfo = null;
  canEdit = true;
  // 问题名称
  title = '';
  // 问题描述
  des = '';
  // 解决办法
  resolvedes = '';
  resolvestate = '0';
  ispublic = false;
  fileArr = [];
  filePath = '';
  previewImage: string | undefined = '';
  previewVisible = false;
  subscriptations = [];
  desData = null;
  geo = null;
  remarkid = uuidv4();
  canModify = true;
  mapboxglmap = null;
  QuewktGeom = '';
  allowDraw = false;
  constructor(private commonService: CommonService,
              private apboxMapService: MapService,
              private shareMessageService: ShareMessageService,
              private styleMapService: StyleService,
              private message: NzMessageService) { }
  ngOnInit() {
    this.apboxMapService.init().then((mapboxglmap: any) => {
      this.mapboxglmap = mapboxglmap;
      if (mapboxglmap.isStyleLoaded()) {
        this.mapinit(mapboxglmap);
      } else {
        mapboxglmap.on('load', () => {
          this.mapinit(mapboxglmap);
        });
      }
    });
    this.remarkid = uuidv4();
    // 增加问题标记
    this.subscriptations.push(
      this.shareMessageService.getMessage().subscribe(e => {
        if (e === 'true') {
          this.allowDraw = true;
        } else {
          this.allowDraw = false;
        }
      }),
      postal.channel('QUESTION_TREE_CHANNEL').subscribe('refrese', res => {
        if (this.questionLayerIsOpen) {
          this.commonService.getQuestionGeojson();
        }
      }),
      // 问题标记的内容需要高亮
      postal.channel('QUESTION-MARK').subscribe('hl-question-mark', res => {
        const highLightQuestionMark = this.styleMapService.getStyleByflag('hl_question_point', res);
        this.apboxMapService.addGeoJSONLayer(highLightQuestionMark, {});
      }),
    );
  }
  mapinit(map) {
    this.mapboxglmap.on('click', (e) => {
      const bbox = [
        [e.point.x - 3, e.point.y - 3],
        [e.point.x + 3, e.point.y + 3]
      ];
      // 问题标记绘制按钮
      if (this.allowDraw) {
        const geometry = `POINT(${e.lngLat.lng} ${e.lngLat.lat})`;
        this.QuewktGeom = geometry;
        this.isVisible = true;
        this.flag = false;
      }
      // 问题标记
      if (this.questionLayerIsOpen && this.commonService.isOpenLayer(this.mapboxglmap, 'questionPointID')) {
        const features = map.queryRenderedFeatures(bbox, {
          layers: ['questionPointID']
        });
        if (features && features.length > 0) {
          const id = features[0].properties.remarkid;
          this.getquestionDetail(id);
        }
      }
    });
  }
  handleCancel(e) {
    this.isVisible = false;
    this.clearData();
    this.allowDraw = false;
    this.QuewktGeom = '';
  }
  handleDesCancel(e) {
    this.isVisible = false;
  }

  handleOk(e) {
    const info = {
      remarkid: this.remarkid,
      title: this.title,
      ispublic: this.ispublic ? 1 : 0,
      des: this.des,
      createby: '',
      resolvestate: this.resolvestate === '0' ? 0 : 1,
      resolvedes: this.resolvedes,
      geo: this.geo
    };
    this.getSubmitInfo(info);
    this.isVisible = false;
    this.clearData();
    // 清除掉绘制的点
    this.allowDraw = false;
    this.QuewktGeom = '';
  }
  // 要提交的信息
  getSubmitInfo(e) {
    if (!e.geo) {
      e.geo = this.QuewktGeom;
    }
    this.commonService.submitQuestion(e).subscribe(res => {
      if (res.code === 1) {
        this.message.info('问题上报成功');
        postal.channel('QUESTION_TREE_CHANNEL').publish('refrese');
      } else {
        this.message.info('问题上报失败');
      }
    });
  }
  getBase64(file: File): Promise<string | ArrayBuffer | null> {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = error => reject(error);
    });
  }
  delFile(index, array) {
    const params = { picId: array[index].id };
    this.commonService.delQuestionPic(params).subscribe(res => {
      if (res.code === 1 && res.data) {
        this.message.info('删除成功！');
      } else {
        this.message.info('删除失败！');
      }
    });
    // 界面上
    array.splice(index, 1);
  }
  public addCheckFile() {
    const input = document.getElementById('picinput') as HTMLInputElement;
    input.onchange = (files: any) => {
      const Tempfile = input.files[0];
      const fr = new FileReader();
      fr.onload = () => {
        const Temp = {
          url: fr.result,
          id: '',
          name: Tempfile.name
        };
        this.fileArr.push(Temp);
        this.getSubmitImg({ remoarkid: this.remarkid, imgData: Temp });
      };
      fr.readAsDataURL(Tempfile);
      // 临时添加  回调将将当前input的value值置空即可
      files.target.value = '';

    };
    input.click();
  }
  getSubmitImg(e) {
    this.commonService.backImgResult(e, (res) => {
      if (res) {
        this.message.info('图片上传成功');
        this.imginfo = res;
      } else {
        this.imginfo = null;
        this.message.info('图片上传失败，请删除重新上传');
      }
    });
  }
  handlePreview(file) {
    this.previewImage = file.url || file.thumbUrl || file.picaddr;
    this.previewVisible = true;
  }
  Preview() {
    const image = new Viewer(document.getElementById(`image`), {
      // 详细的参数设置参见
      title: false,  // 是否显示标题
      fullscreen: false,  // 播放时是否全屏
      rotatable: true,  // 图片是否可旋转
      scalable: true,  // 图片是否可翻转
      maxZoomRatio: 3  // 最大缩放比例
   });
  }
  clearData() {
    // 一定要重新更新uuid，不然就会修改数据库中uuid为某值的内容！
    this.remarkid = uuidv4();
    this.title = '';
    // 问题描述
    this.des = '';
    // 解决办法
    this.resolvedes = '';
    this.resolvestate = '0';
    this.ispublic = false;
    this.fileArr = [];
    this.geo = '';
  }
  // 判断拿到的data是否有变换，然后赋值给当前页面
  ngOnChanges(changes: SimpleChanges) {
    if (changes.questionLayerIsOpen && changes.questionLayerIsOpen.currentValue) {
      this.questionLayerIsOpen =  changes.questionLayerIsOpen.currentValue;
    }
  }
  // 用户点击编辑的时候的操作
  update(e) {
    this.flag = !this.flag;
    // 标题
    this.title = this.desData.title;
    this.remarkid = this.desData.remarkid;
    // 问题描述
    this.des = this.desData.des;
    // 解决状态
    this.resolvestate = (this.desData.resolvestate).toString();
    // 是否公开
    if (this.desData.ispublic === 1) {
      this.ispublic = true;
    } else {
      this.ispublic = false;
    }
    this.geo = this.desData.geo;
    // 解决办法
    this.resolvedes = this.desData.resolvedes;
    // 图片
    this.fileArr = [];
    this.desData.picInfo.forEach(element => {
      const Temp = {
        url: element.picaddr,
        id: element.picid,
        name: element.name,
      };
      this.fileArr.push(Temp);
    });
  }
  getquestionDetail(id) {
    this.commonService.getQuestionDetail({ remarkId: id }).subscribe(res => {
      if (res.code === 1 && res.data) {
        this.desData = res.data.result;
        this.isVisible = true;
        this.flag = true;
        this.canModify = res.data.isEditor;
      } else {
        this.canModify = true;
        this.isVisible = false;
        this.flag = false;
      }
    });
  }
  // 如果期望其再出来的话，我不能在这里出现销毁内容，只能取消订阅！
  ngOnDestroy() {
    this.clearData();
    this.subscriptations.forEach(element => {
        element.unsubscribe();
    });
    this.questionLayerIsOpen = null;
  }
}
